<?php

namespace common\logics\article;

use Yii;

/**
 * 首页资讯
 * 
 * @author emhome <emhome@163.com>
 * @since 1.0
 */
class HomeArticleLogic extends BaseArticleLogic {

    /**
     * @inheritdoc
     */
    public function buildQuery($alias = 't') {
        $query = static::find()->alias($alias);
        if ($alias) {
            $alias .= '.';
        }
        $query->andWhere([
            $alias . 'deleted_at' => null,
        ]);
        //全局移除活动资讯
        $query->andFilterWhere([
            'not in', $alias . 'category_id', $this->getRemoveCategoryIds()
        ]);

        $rootId = $this->getRootId();
        $unionId = $this->getUnionId();

        //限制基础资讯权限
        $query->innerJoinWith([
            'unionModels' => function ($q) use($rootId, $unionId) {
                /* @var $q \yii\db\ActiveQuery */
                $q->alias('unionModels')->andWhere([
                    'unionModels.model' => 'post'
                ])->andWhere([
                    'or',
                    [
                        'and',
                        ['unionModels.union_id' => $unionId],
                        ['unionModels.root_id' => $rootId],
                    ],
                    ['unionModels.root_id' => 0],
                ]);
            }
        ]);

        //区分root栏目
        $query->andWhere([$alias . 'category_id' => $this->getRootCategoryIds()]);

        $query->orderBy([
            $alias . 'top' => SORT_DESC,
            $alias . 'public_at' => SORT_DESC,
        ]);
        return $query;
    }

}
